Ext.namespace('Ext.ux.form');

/*
 * extend setTimeout function to support arguments
 */
function setTimeoutEx(fRef, mDelay) {
	if (typeof fRef == 'function') {
		var args = Array.prototype.slice.call(arguments, 2);
		var f = function() {
			fRef.apply(null, args);
		};
		return setTimeout(f, mDelay);
	}
	return setTimeout(fRef, mDelay);
}

Ext.ux.form.FCKeditor = function(config) {
	if (config.id == null) {
		config.id = '__fckeditor_' + parseInt(1000 * Math.random());
	}
	this.config = config;
	this.fckconfig = config;
	Ext.ux.form.FCKeditor.superclass.constructor.call(this, config);
	this.instanceLoaded = false;
	this.instanceValue = config.value ? config.value : '';
	this.editorInstance = undefined;
};

Ext.extend(Ext.ux.form.FCKeditor, Ext.form.TextArea, {
			initEvents : function() {
				this.on('destroy', function() {
							if (typeof this.editorInstance != 'undefined') {
								delete this.editorInstance;
							}
						});
			},
			onRender : function(ct, position) {
				if (!this.el) {
					this.defaultAutoCreate = {
						tag : "textarea",
						style : "width:300px;height:660px;",
						autocomplete : "off"
					};
				}
				Ext.form.TextArea.superclass.onRender.call(this, ct, position);
				this.hideMode = "visibility";

				this.hidden = true;
				if (this.grow) {
					this.textSizeEl = Ext.DomHelper.append(document.body, {
								tag : "pre",
								cls : "x-form-grow-sizer"
							});
					if (this.preventScrollbars) {
						this.el.setStyle("overflow", "hidden");
					}
					this.el.setHeight(this.growMin);
				}
				setTimeoutEx(loadFCKeditor, 100, this.config.id, this.fckconfig);
			},
			setIsLoaded : function(v) {
				this.instanceLoaded = v;
			},
			getIsLoaded : function() {
				return this.instanceLoaded;
			},
			setValue : function(value) {
				this.instanceValue = value;
				if (this.instanceLoaded) {
					this.FCKeditorSetValue(value);
				}
				Ext.form.TextArea.superclass.setValue.apply(this, [value]);
			},
			// 获得输入框的内容 @author wei.tao
			getValue : function() {
				if (this.instanceLoaded) {
					value = this.FCKeditorGetValue();
					Ext.form.TextArea.superclass.setValue.apply(this, [value]);
					return Ext.form.TextArea.superclass.getValue.call(this);
				} else {
					return this.instanceValue;
				}
			},
			getRawValue : function() {
				if (this.instanceLoaded) {
					value = this.FCKeditorGetValue();
					Ext.form.TextArea.superclass.setRawValue.apply(this,
							[value]);
					return Ext.form.TextArea.superclass.getRawValue.call(this);
				} else {
					return this.instanceValue;
				}
			},
			FCKeditorSetValue : function(value) {
				if (this.instanceLoaded == false) {
					return;
				}
				var runner = new Ext.util.TaskRunner();
				var task = {
					run : function() {
						try {
							var editor = this.editorInstance;
							if (editor.EditorDocument.body) {
								editor.SetData(value);
								runner.stop(task);
							}
						} catch (ex) {
						}
					},
					interval : 100,
					scope : this
				};
				runner.start(task);
			},
			FCKeditorGetValue : function() {
				var data = '';
				if (this.instanceLoaded == false) {
					return data;
				}
				data = this.editorInstance.GetData();
				return data;
			},
			isDirty : function() {
				return this.editorInstance.IsDirty();
			},
			resetIsDirty : function() {
				this.editorInstance.ResetIsDirty();
			},
			// 验证长度(字符) @author wei.tao
			fckValidateLength : function(value) {
				return value;
			},
			// 是否验证成功 @author wei.tao
			validateIsSuccess : true
		});
Ext.reg('fckeditor', Ext.ux.form.FCKeditor);
// 加载js
ScriptLoader = function() {
	this.timeout = 10;
	this.scripts = [];
	this.disableCaching = true;
	this.loadMask = null;
};
ScriptLoader.prototype = {
	showMask : function() {
		if (!this.loadMask) {
			this.loadMask = new Ext.LoadMask(Ext.getBody());
			this.loadMask.show();
		}
	},
	hideMask : function() {
		if (this.loadMask) {
			this.loadMask.hide();
			this.loadMask = null;
		}
	},
	processSuccess : function(a) {
		if (typeof a.argument.callback == "function") {
			a.argument.callback.call(a.argument.scope, a.responseText,
					a.argument.url, a.argument.index);
		}
	},
	processFailure : function(a) {
		this.hideMask();
		Ext.MessageBox.show({
					title : "应用程序出错",
					msg : "Js脚本库加载出错，服务器可能停止，请联系管理员。文件路径：" + a.argument.url,
					closable : false,
					icon : Ext.MessageBox.ERROR,
					minWidth : 200
				});
	},
	load : function(c, e) {
		var a, d, b;
		if (typeof c == "object") {
			a = c;
			c = a.url;
			b = a.index;
			e = e || a.callback;
			d = a.scope;
			if (typeof a.timeout != "undefined") {
				this.timeout = a.timeout;
			}
			if (typeof a.disableCaching != "undefined") {
				this.disableCaching = a.disableCaching;
			}
		}
		if (this.scripts[c]) {
			if (typeof e == "function") {
				e.call(d || window);
			}
			return null;
		}
		this.showMask();
		Ext.Ajax.request({
					url : c,
					success : this.processSuccess,
					failure : this.processFailure,
					scope : this,
					timeout : (this.timeout * 1000),
					disableCaching : this.disableCaching,
					argument : {
						"url" : c,
						"scope" : d || window,
						"callback" : e,
						"options" : a,
						"index" : b
					}
				});
	}
};
ScriptLoaderMgr = function() {
	this.mdCache = [];
	this.loader = new ScriptLoader();
	var loader = this.loader;
	this.load = function(o) {
		this.loader.scope = o.scope;
		if (!Ext.isArray(o.scripts)) {
			o.scripts = [o.scripts];
		}
		o.lfiles = 0;
		this.mdCache.length = 0;
		var mdCache = this.mdCache;
		for (var i = 0; i < o.scripts.length; i++) {
			o.url = o.scripts[i];
			o.index = i;
			this.loader.load(o, function(rs, url, idx) {
						o.scope = this;
						mdCache[idx] = {
							content : rs
						};
						o.lfiles++;
						if (o.lfiles >= o.scripts.length) {
							for (var j = 0; j < mdCache.length; j++) {
								try {
									window.execScript
											? window
													.execScript(mdCache[j].content)
											: window.eval(mdCache[j].content);
								} catch (ex) {
								}
							}
							loader.hideMask();
							if (o.callback != null) {
								o.callback.call(this);
							}
						}
					});
		}
	};
};
ScriptMgr = new ScriptLoaderMgr();

function $ImportSimpleJs(a, c, b) {
	ScriptMgr.load({
				scripts : a,
				scope : b,
				callback : function() {
					if (c) {
						c.call(this);
					}
				}
			});
}

function loadFCKeditor(element, config) {
	// 加载fckEditor js
	$ImportSimpleJs([__ctxPath + '/ext/ux/fckeditor/fckeditor.js'], function() {
				var oFCKeditor = new FCKeditor(element, config.width,
						config.height);
				for (var key in config) {
					if (typeof oFCKeditor[key] != 'undefined') {
						oFCKeditor[key] = config[key];
					}
				}
				oFCKeditor.BasePath = __ctxPath + '/ext/ux/fckeditor/';
				oFCKeditor.ToolbarSet = 'JDefault';
				oFCKeditor.ReplaceTextarea();
			});
}

// FCK加载完毕后会自动调用名字为FCKeditor_OnComplete的函数;
// 将自身作为参数传递进来 @author wei.tao
function FCKeditor_OnComplete(editorInstance) {
	var activeEditor = Ext.getCmp(editorInstance.Name);
	activeEditor.editorInstance = editorInstance;
	activeEditor.instanceLoaded = true;
	activeEditor.FCKeditorSetValue(activeEditor.instanceValue);
	// 附加的事件
	editorInstance.Events.AttachEvent('OnBlur', FCKeditor_onchange);
}

// 对输入的内容进行验证 @author wei.tao
function FCKeditor_onchange(editorInstance) {
	var activeEditor = Ext.getCmp(editorInstance.Name);
	activeEditor.validateIsSuccess = true;// 验证默认通过属性为false
	var fckeditorContentLength = editorInstance.GetXHTML(true).length;
	// 验证提示 @author wei.tao
	if (fckeditorContentLength > 0) {
		var dd = editorInstance.GetXHTML(true).replace(/<\/?.+?>/g, "");
		var dds = dd.replace(/(^＼s*)|(＼s*$)/g, "").replace(/&nbsp;/g, "");// dds为得到去掉标签特殊符号后文字的内容
		var length = dds.replace(/[^\x00-\xff]/g, "**").length// 字符的个数
		if (length > activeEditor.fckValidateLength) {
			// alert("此文本只能输入" + Math.floor(activeEditor.fckValidateLength / 2)
			// + "个汉字以内(即" + activeEditor.fckValidateLength
			// + "个字符以内),你已输入" + Math.floor(length / 2) + "个汉字");
			activeEditor.validateIsSuccess = false;// 验证是否通过属性为false
		} else {
			activeEditor.validateIsSuccess = true;// 验证是否通过属性为false
		}
	}
}
